#include <iostream>
#include <sstream>
#include <string>
#include <GL/gl.h>
#include <GL/glu.h>
#include "AppWeatherView.h"
#include <UIEngine.h>
#include <UIWindow.h>
#include <UIJPGImage.h>
#include <UIText.h>


#include "Weather.h"
#include "AppWeatherModel.h"

std::string getRealName(std::string name){
  size_t index = name.find_last_of(".");
  std::string ret(name.substr(0,index)+".jpg");
  return ret;
}

AppWeatherView::AppWeatherView():_loaded(false) {
  _model.loadTownForecast("Grenoble");
  //_pictures = _model.getForecast();
  _ui = new UIEngine(RGBAColor(0.1, 0.1, 0.1, 1.), RGBAColor(0., 0., 0., 1.), 2.
		     ,2., 0., 0.);
 
}

void render_string(float x, float y, float z, void* font, const char* s)
{
  glDisable(GL_TEXTURE_2D);
  glDisable(GL_DEPTH_TEST);
  glColor3f(1.,1.,1.);
  glRasterPos2f(x, y);
  while(*s)
    {
      glutBitmapCharacter(font, *s);
      s++;
    }
  glEnable(GL_DEPTH_TEST);
  glEnable(GL_TEXTURE_2D);
}

void AppWeatherView::displayFront() {
  commonGL();
  _ui->display();
  //glPushMatrix(); glScalef(2,2,1);
  render_string(0.,2.,-0.8, GLUT_BITMAP_HELVETICA_18,"Weather");
  render_string(0.,1.95,-0.8, GLUT_BITMAP_HELVETICA_18,
		_model.getLocation().c_str());
  //glPopMatrix();
  std::list<Weather*> l = _model.getForecast();
  float posY = 1.6;
  for(std::list<Weather*>::iterator it = l.begin();
      it != l.end();
      it++){
    
    render_string(0.3,posY,-0.8, GLUT_BITMAP_HELVETICA_18,
		  ((*it)->getDay()).c_str());
    render_string(0.3,posY-0.05,-0.8, GLUT_BITMAP_HELVETICA_12,
		  ((*it)->getCondition()).c_str());
    
    std::ostringstream temp_l;
    temp_l << "Lower temperature: " << (*it)->getTemperatureLowC() << "C";
    render_string(0.1,posY,-0.8, GLUT_BITMAP_HELVETICA_18,temp_l.str().c_str());
    
    std::ostringstream temp_h;
    temp_h << "Higher temperature: " << (*it)->getTemperatureHighC() << "C";
    render_string(0.1,posY-0.05,-0.8, GLUT_BITMAP_HELVETICA_18,temp_h.str().c_str());

    posY -= 0.4;
    
 
    
  }

}

void AppWeatherView::displayBack() {
  commonGL();
  _ui->display();
  //this->displayFront();
}

void AppWeatherView::transitive(float percent) {
  commonGL();
  _ui->display();
  // this->displayFront();
}

AppWeatherView::~AppWeatherView() {
  delete _ui;
}

void AppWeatherView::commonGL(){
 if(!_loaded){
   float posY = 1.5;
   _ui->addUIComponent(new UIWindow(-1., 0., "App Weather"));
   std::list<Weather*> l = _model.getForecast();
   for(std::list<Weather*>::iterator it = l.begin();
       it != l.end();
       it++){
     
     _ui->addUIComponent(new UIJPGImage(0.7, posY, 0.15, 0.15,
					getRealName((*it)->getIcon())));
     posY -= 0.4;
     std::cout << (*it)->getIcon();
   } 
    _loaded = true;
  }
}
